package topofstack.networkserverutils.net;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import topofstack.networkserverutils.bean.SiteInfo;
import topofstack.networkserverutils.util.ShellEmulator;
import android.util.Log;

public class Nslookup {
	public static String get(String url) {
		String command = "nslookup " + url;
		String result = ShellEmulator.query(command);
		
		return result;
	}
	
	public static List<String> getMX(String url) {
		String command = "nslookup -type=MX " + url;
		String result = ShellEmulator.query(command);
		
		return parseMX(result);
	}
	
	public static SiteInfo getA(String url) {
		String command = "nslookup -type=A " + url;
		String result = ShellEmulator.query(command);
		
		return parseA(result);
	}
	
	private static List<String> parseMX(String input) {
		if(input == null)
			return null;
		
		List<String> result = new ArrayList<String>();
		BufferedReader reader = new BufferedReader(new StringReader(input));
		String line;
		boolean found = false;
		
		try {
			while((line = reader.readLine()) != null) {
				if(found && line.contains("mail exchanger")) {
					String[] contents = line.trim().split(" ");
					result.add(contents[contents.length - 1]);
				}
				else if(line.contains("answer:"))
					found = true;
			}
		} catch(Exception exception) {
			exception.printStackTrace();
			return null;
		}
		
		Log.d("MX", result.toString());
		return result;
	}
	
	private static SiteInfo parseA(String input) {
		if(input == null)
			return null;
		
		BufferedReader reader = new BufferedReader(new StringReader(input));
		String line;
		String name;
		String ipAddress;
		
		SiteInfo siteInfo = null;
		
		try {
			while((line = reader.readLine()) != null) {
				if(line.contains("Name:")) {
					String[] contents = line.trim().split("[ \t]");
					name = contents[contents.length - 1];
					line = reader.readLine();
					contents = line.trim().split("[ \t]");
					ipAddress = contents[contents.length - 1];
					
					siteInfo = new SiteInfo(name, ipAddress);
					break;
				}
			}
		} catch(Exception exception) {
			exception.printStackTrace();
			return null;
		}
		
		Log.d("SiteInfo", siteInfo.toString());
		return siteInfo;
	}
}
